package com.example.studentknowledge.repository;

import com.example.studentknowledge.entity.Article;
import com.example.studentknowledge.entity.Attachment;
import com.example.studentknowledge.entity.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 附件Repository接口
 */
@Repository
public interface AttachmentRepository extends JpaRepository<Attachment, Long> {
    
    /**
     * 根据文章查找附件
     */
    List<Attachment> findByArticleOrderByCreatedAtDesc(Article article);
    
    /**
     * 根据上传者查找附件
     */
    Page<Attachment> findByUploaderOrderByCreatedAtDesc(User uploader, Pageable pageable);
    
    /**
     * 根据文件类型查找附件
     */
    Page<Attachment> findByFileTypeOrderByCreatedAtDesc(String fileType, Pageable pageable);
    
    /**
     * 根据文件名模糊查询
     */
    @Query("SELECT a FROM Attachment a WHERE a.fileName LIKE %:keyword% ORDER BY a.createdAt DESC")
    Page<Attachment> findByFileNameContaining(@Param("keyword") String keyword, Pageable pageable);
    
    /**
     * 增加下载次数
     */
    @Modifying
    @Query("UPDATE Attachment a SET a.downloadCount = a.downloadCount + 1 WHERE a.id = :id")
    void incrementDownloadCount(@Param("id") Long id);
    
    /**
     * 统计用户上传的文件数
     */
    @Query("SELECT COUNT(a) FROM Attachment a WHERE a.uploader = :uploader")
    Long countByUploader(@Param("uploader") User uploader);
    
    /**
     * 统计文章的附件数
     */
    @Query("SELECT COUNT(a) FROM Attachment a WHERE a.article = :article")
    Long countByArticle(@Param("article") Article article);
    
    /**
     * 获取热门下载文件
     */
    @Query("SELECT a FROM Attachment a ORDER BY a.downloadCount DESC")
    List<Attachment> findPopularAttachments(Pageable pageable);
    
    /**
     * 获取最新上传的文件
     */
    @Query("SELECT a FROM Attachment a ORDER BY a.createdAt DESC")
    List<Attachment> findLatestAttachments(Pageable pageable);
}